package com.xinzhi.controller;

import com.xinzhi.anno.CheckRole;
import com.xinzhi.domain.User;
import com.xinzhi.service.LoginService;
import com.xinzhi.service.UserService;
import com.xinzhi.utils.FileUtil;
import com.xinzhi.utils.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@CrossOrigin
@RequestMapping("/api/file")
@RestController
@Slf4j
@RequiredArgsConstructor
public class FileController {
    @Autowired
    UserService userService;
    @Autowired
    LoginService loginService;
    @CheckRole(role = {"user"})
    @PostMapping("/uploads")
    public Result uploads(MultipartFile file, HttpServletRequest request) throws IOException{
        User token = loginService.checkToken(request.getHeader("token"));
        if (token != null) {
            if (file != null) {
                String url = FileUtil.uploads(file, request);
                return userService.upheadshot(url, token.getUserId());
            }
            return Result.error(5002, "请选择要上传的文件！");
        }
        return Result.error("token为空");
    }
    @PostMapping("/upload")
    public Result upload(MultipartFile file, HttpServletRequest request) throws IOException{
            if (file != null) {
                String url = FileUtil.uploads(file, request);
                return Result.ok(url);
            }
            return Result.error(5002, "请选择要上传的文件！");
        }
}
